package com.zw.cloud.common.thread.local;

import com.alibaba.ttl.TransmittableThreadLocal;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 *  TtlRunnable
 *  TtlCallable
 * getTtlExecutor：修饰接口Executor
 * getTtlExecutorService：修饰接口ExecutorService
 * getTtlScheduledExecutorService：修饰接口ScheduledExecutorService
 */
public class TransmittableThreadLocalUtils {
    protected static final TransmittableThreadLocal<Map<String,String>> THREAD_LOCAL = new TransmittableThreadLocal<>(){
        protected Map<String, String> initialValue() {
            return (Map<String, String>) new ConcurrentHashMap();
        }
    };
    public static String getValue(String key) {
        if (Objects.isNull(THREAD_LOCAL.get())) {
            return null;
        }
        return (String)((Map)THREAD_LOCAL.get()).get(key);
    }

    public static void setValue(String key, String value) {
        if (Objects.nonNull(THREAD_LOCAL.get()) && Objects.nonNull(key) && Objects.nonNull(value)) {
            ((Map)THREAD_LOCAL.get()).put(key, value);
        }
    }

    public static void clear() {
        THREAD_LOCAL.remove();
    }
}
